package com.yuewen.mongodb.dao;

import com.mongodb.Mongo;
import com.mongodb.WriteResult;
import com.yuewen.mongodb.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.net.UnknownHostException;

/**
 * Created by francis on 2017/3/18.
 */
public class MongoDao {
    public MongoDao() {
        Mongo mongo= null;
        try {
            mongo = new Mongo("192.168.222.130", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        mongoTemplate = new MongoTemplate(mongo, "db_dev");
    }

    /**
     * 定义集合名称
     */
    private static String HELLOKITTY = "User";

    /**
     * 操作MongoDB的对象
     */
    private MongoTemplate mongoTemplate;


    public void createHelloKitty(User hello) {
        mongoTemplate.insert(hello, HELLOKITTY);
    }

    public User getHelloKittyByName(String name) {
        return mongoTemplate.findOne(new Query(Criteria.where("name").is(name)), User.class, HELLOKITTY);
    }
    public int deleteByName(String name){
        WriteResult er=  mongoTemplate.remove(new Query(Criteria.where("name").is(name)), User.class, HELLOKITTY);
        return er.getN();
    }
}
